﻿using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using WorkflowCoreDockingDemo.EntityFrameworkCore.Utils;

namespace Microsoft.Extensions.Configuration
{
    public static class ConfigurationExtension
    {
        public static string GetCustomConnectionString(this IConfiguration configuration)
        {
            var originalConnectionString = configuration.GetValueFromManyChanels("ConnectionStrings:Default");
            configuration["ConnectionStrings:Default"] = originalConnectionString;
            var isEncrypt = configuration.GetValueFromManyChanels("ConnectionStrings:IsEncrypt");
            if (!string.IsNullOrWhiteSpace(isEncrypt))
            {
                var key = configuration.GetValueFromManyChanels("ConnectionStrings:Secret");
                if (string.IsNullOrWhiteSpace(key))
                {
                    var secretPath = configuration["ConnectionStrings:SecretPath"];
                    key = File.ReadAllText(secretPath, Encoding.UTF8);

                }
                var str = AESHelper.Decrypt(originalConnectionString, key, key);
                configuration["ConnectionStrings:Default"] = str;
                return str;
            }
            return originalConnectionString;
        }
    }
}
